const _ = require("lodash");

function select32NumbersBySmartStrategy(temp) {
  const allNumbers = Array.from({ length: 49 }, (_, i) =>
    (i + 1).toString().padStart(2, "0")
  );

  // 1️⃣ 建立每个号码出现的索引列表
  const historyMap = {};
  temp.forEach((item, idx) => {
    if (!historyMap[item.number]) historyMap[item.number] = [];
    historyMap[item.number].push(idx);
  });

  // 2️⃣ 计算平均周期（近几次间隔）
  const cycleMap = {};
  for (const num of allNumbers) {
    const indices = historyMap[num] || [];
    if (indices.length < 2) {
      cycleMap[num] = 999; // 极大周期
      continue;
    }
    const gaps = [];
    for (let i = 1; i < indices.length; i++) {
      gaps.push(indices[i] - indices[i - 1]);
    }
    const avgGap = _.mean(gaps);
    cycleMap[num] = avgGap;
  }

  // 3️⃣ 连错淘汰机制：剔除连续 5 次都没中的号码
  const wrongCountMap = {};
  for (const num of allNumbers) {
    wrongCountMap[num] = 0;
    for (let i = temp.length - 5; i < temp.length; i++) {
      if (i < 0) continue;
      if (temp[i].number !== num) {
        wrongCountMap[num]++;
      } else {
        wrongCountMap[num] = 0;
        break; // 有中断，不计错
      }
    }
  }

  // 4️⃣ 综合评分（周期越短越好 + 连错惩罚）
  const scoreList = allNumbers.map((num) => {
    const baseScore = 1000 / cycleMap[num]; // 周期越短分越高
    const penalty = wrongCountMap[num] >= 5 ? -9999 : 0;
    return { num, score: baseScore + penalty };
  });

  // 5️⃣ 选择得分最高的前 32 个
  const finalNumbers = scoreList
    .sort((a, b) => b.score - a.score)
    .map((x) => x.num)
    .slice(0, 32);

  return finalNumbers;
}

module.exports = select32NumbersBySmartStrategy;
